package com.nageoffer.shortlink.project.service.impl;

import com.nageoffer.shortlink.project.service.UrlTitleService;
import lombok.SneakyThrows;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.springframework.stereotype.Service;

import java.net.HttpURLConnection;
import java.net.URL;

// URL标题服务实现类
@Service
public class UrlTitleServiceImpl implements UrlTitleService {

    // 通过URL获取网页标题（自动处理异常）
    @SneakyThrows
    @Override
    public String getTitleByUrl(String url) {
        // 将字符串URL转换为URL对象
        URL targetUrl = new URL(url);

        // 创建HTTP连接对象
        HttpURLConnection connection = (HttpURLConnection) targetUrl.openConnection();
        // 设置请求方法为GET
        connection.setRequestMethod("GET");
        // 建立实际连接
        connection.connect();

        // 获取HTTP响应码
        int responseCode = connection.getResponseCode();
        // 判断响应是否成功（HTTP 200）
        if (responseCode == HttpURLConnection.HTTP_OK) {
            // 使用JSoup解析网页内容
            Document document = Jsoup.connect(url).get();
            // 返回网页标题
            return document.title();
        }
        // 请求失败时返回错误信息
        return "Error while fetching title.";
    }
}